/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { cart, store } from "@mall/api-services"
import * as _ from "lodash"
import { observer } from "mobx-react"
import * as React from "react"
import { RouteComponentProps, withRouter } from "react-router"
import Checkbox from "../components/checkbox"
import Flex from "../components/flex"
import InputNumber from "../components/input-number"
import ProductPrice from "../components/product/product-price"
import Icon from "../icon"

import "./index.scss"
import * as state from "./state"

interface CartItemProps extends RouteComponentProps {
  item: cart.CartItem;
  cart: state.Cart;
}

interface CartItemState {
  product?: store.Product;
}

@observer
class CartItem extends React.Component<CartItemProps, CartItemState> {

  constructor(props: Readonly<CartItemProps>) {
    super(props)
    this.state = {}
  }

  public componentDidMount(): void {
    store.ProductServiceV1
      .getProduct(this.props.item.productId)
      .then(product => this.setState({ product }))
  }

  public render() {
    const { cart, item } = this.props
    const { product } = this.state
    if (product === undefined) {
      return <></>
    }

    const variant = product.getVariant(item.variantId)
    if (variant === undefined) {
      return <></>
    }

    item.price = variant.price
    item.imageUrl = variant.imageUrls[0]
    item.optionSelections = variant.optionSelections
    item.name = product.name

    return (
      <div className="cart-item">
        <Checkbox className="cart-item-checkbox" checked={cart.contains(item)}
                  onChange={e => {
                    e.stopPropagation()
                    if (e.target.checked) {
                      cart.add(item)
                    } else {
                      cart.remove(item)
                    }
                  }}/>
        <Flex>
          <div className="cart-item-image" onClick={this.handleToProduct}>
            <img alt="" src={item.imageUrl}/>
          </div>
          <div className="cart-item-content">
            {this.renderProductName(product?.name)}
            <div>
              <span className="cart-item-options" onClick={e => e.stopPropagation()}>
                {_.chain(item.optionSelections).map(selection => selection.value).join(",").value()}
                <Icon type="right" size="xxs"/>
              </span>
            </div>
            <div style={{
              display: "flex",
              flexDirection: "row",
              justifyContent: "space-between",
            }}>
              <ProductPrice price={variant.price} size={16}/>
              <InputNumber value={item.quantity} style={{ height: "16px" }}
                           onClick={e => e.stopPropagation()}/>
            </div>
          </div>
        </Flex>
      </div>
    )
  }

  private readonly renderProductName = (name: string | undefined) => {

    return name && <span className="cart-item-name" onClick={this.handleToProduct}>
                {name.length > 40 ? name.substr(0, 40) + "..." : name}
            </span>
  }

  private readonly handleToProduct = () => {
    const { product } = this.state
    const { history } = this.props
    history.push(`/products/${product?.id}`)
  }
}

export default withRouter(CartItem)
